#include "tslib_drv.h"
#include <stdio.h>

static struct tsdev *ts;

// 定义去抖动相关的静态变量
static int16_t last_x = 0;
static int16_t last_y = 0;
static lv_indev_state_t last_state = LV_INDEV_STATE_REL;
static uint32_t last_time = 0;

// 去抖动阈值设置
#define DEBOUNCE_THRESHOLD_DIST 5     // 距离阈值（像素）
#define DEBOUNCE_THRESHOLD_TIME 200   // 时间阈值（毫秒）

void tslib_read(lv_indev_drv_t *drv, lv_indev_data_t *data) {
    struct ts_sample sample;
    if (ts_read(ts, &sample, 1) == 1) {
        uint32_t curr_time = lv_tick_get();
        lv_indev_state_t curr_state = (sample.pressure > 0) ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
        
        // 计算当前触摸点与上一次触摸点的距离
        int16_t dx = abs(sample.x - last_x);
        int16_t dy = abs(sample.y - last_y);
        
        // 检查状态变化
        if (curr_state != last_state) {
            if (curr_state == LV_INDEV_STATE_PR && 
                curr_time - last_time > DEBOUNCE_THRESHOLD_TIME) {
                // 新的按下事件，且与上次释放间隔足够长
                data->point.x = sample.x;
                data->point.y = sample.y;
                data->state = curr_state;
                
                last_x = sample.x;
                last_y = sample.y;
                last_state = curr_state;
                last_time = curr_time;
            } else if (curr_state == LV_INDEV_STATE_REL) {
                // 释放事件
                data->point.x = last_x;
                data->point.y = last_y;
                data->state = curr_state;
                
                last_state = curr_state;
                last_time = curr_time;
            }
        } else if (curr_state == LV_INDEV_STATE_PR && 
                   (dx > DEBOUNCE_THRESHOLD_DIST || dy > DEBOUNCE_THRESHOLD_DIST)) {
            // 按下状态下的移动
            data->point.x = sample.x;
            data->point.y = sample.y;
            data->state = curr_state;
            
            last_x = sample.x;
            last_y = sample.y;
            last_time = curr_time;
        }
        return;
    }
    return;
}

int tslib_init(void) {
    // 使用 ts_open 手动打开触摸屏设备
    ts = ts_open("/dev/input/touchscreen0", 1);
    if (!ts) {
        perror("Failed to open touchscreen device");
        return -1;
    }

    // 配置 tslib（加载校准参数等）
    if (ts_config(ts) < 0) {
        perror("Failed to configure tslib");
        ts_close(ts);
        return -1;
    }
    return 0;
}